<template>
  <el-dialog
      v-model="dialogVisible"
      title="创建主题学习"
      width="700px"
      :before-close="handleCancel"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
    >
      <!-- 第一行：主题名称 + 主题类别 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="主题名称" prop="name">
            <el-input
                v-model="form.name"
                placeholder="请输入主题名称"
                maxlength="50"
                show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主体类别" prop="category">
            <el-select
                v-model="form.category"
                placeholder="请选择主体类别"
                style="width: 100%"
            >
              <el-option
                  v-for="theme in themeCategories"
                  :key="theme.name"
                  :label="theme.label"
                  :value="theme.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：主题封面（独占一行） -->
      <el-form-item label="主题封面" prop="coverImage">
        <el-upload
            class="cover-upload"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleCoverChange"
            accept="image/*"
        >
          <div v-if="form.coverImage" class="cover-preview">
            <img :src="form.coverImage" alt="封面预览" class="cover-image">
            <div class="cover-overlay">
              <el-icon><Camera /></el-icon>
              <span>更换封面</span>
            </div>
          </div>
          <div v-else class="cover-placeholder">
            <el-icon><Plus /></el-icon>
            <div class="cover-text">上传封面图片</div>
          </div>
        </el-upload>
        <div class="cover-tips">建议尺寸：800x400px，支持 JPG、PNG 格式</div>
      </el-form-item>

      <!-- 第三行：学习方式 + 考察方式 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学习方式" prop="learningMethod">
            <el-input
                v-model="form.learningMethod"
                placeholder="请输入学习方式"
                maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考察方式" prop="assessmentMethod">
            <el-input
                v-model="form.assessmentMethod"
                placeholder="请输入考察方式"
                maxlength="100"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行：教育课时 + 授课方式 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="教育课时" prop="hours">
            <el-input-number
                v-model="form.hours"
                :min="1"
                :max="100"
                placeholder="请输入教育课时"
                style="width: 100%"
            />
            <span class="unit-text">课时</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="授课方式" prop="teachingMethod">
            <el-input
                v-model="form.teachingMethod"
                placeholder="请输入授课方式"
                maxlength="100"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行：授课地点（独占一行） -->
      <el-form-item label="授课地点" prop="location">
        <el-input
            v-model="form.location"
            placeholder="请输入授课地点"
            maxlength="100"
        />
      </el-form-item>

      <!-- 第六行：主题描述（独占一行） -->
      <el-form-item label="主题描述" prop="description">
        <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入主题描述"
            maxlength="300"
            show-word-limit
        />
      </el-form-item>

      <!-- 第七行：主题内容（独占一行） -->
      <el-form-item label="主题内容" prop="content">
        <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入主题详细内容（后续将替换为富文本编辑器）"
            maxlength="2000"
            show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定创建
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { Camera, Plus } from '@element-plus/icons-vue'
import { uploadImage, createSubTheme } from '@/api/teacher'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  themeOptions: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'submit', 'cancel'])

// 对话框显示状态
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const form = ref({
  name: '',
  category: '',  // 这个就是themeId
  coverImage: '',
  learningMethod: '',
  assessmentMethod: '',
  hours: 1,
  teachingMethod: '',
  location: '',
  description: '',
  content: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入主题名称', trigger: 'blur' },
    { min: 2, max: 50, message: '主题名称长度为2-50个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择主体类别', trigger: 'change' }
  ],
  coverImage: [
    { required: true, message: '请上传主题封面', trigger: 'change' }
  ],
  learningMethod: [
    { required: true, message: '请输入学习方式', trigger: 'blur' }
  ],
  assessmentMethod: [
    { required: true, message: '请输入考察方式', trigger: 'blur' }
  ],
  hours: [
    { required: true, message: '请输入教育课时', trigger: 'blur' }
  ],
  teachingMethod: [
    { required: true, message: '请输入授课方式', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入授课地点', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入主题描述', trigger: 'blur' },
    { min: 10, max: 300, message: '主题描述长度为10-300个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入主题内容', trigger: 'blur' },
    { min: 20, max: 2000, message: '主题内容长度为20-2000个字符', trigger: 'blur' }
  ]
}

// 主题类别选项
const themeCategories = ref([])

// 监听父组件传递的themeOptions
watch(() => props.themeOptions, (newVal) => {
  themeCategories.value = newVal
}, { immediate: true })

// 封面上传处理
const handleCoverChange = async (file) => {
  try {
    const response = await uploadImage(file.raw)

    if (response.success) {
      // 使用服务器返回的文件路径拼接完整URL
      const baseUrl = 'http://localhost:8080'
      form.value.coverImage = baseUrl + '/uploads' + response.data.filePath
      ElMessage.success('封面图片上传成功')
    } else {
      ElMessage.error(response.message || '图片上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
  }
}

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
})

// 监听dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:modelValue', newVal)
  if (!newVal) {
    resetForm()
  }
})

// 重置表单
const resetForm = () => {
  form.value = {
    name: '',
    category: '',
    coverImage: '',
    learningMethod: '',
    assessmentMethod: '',
    hours: 1,
    teachingMethod: '',
    location: '',
    description: '',
    content: ''
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false
  emit('cancel')
}

// 提交表单 - 创建子主题
// 修改提交方法
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (valid) {
      loading.value = true

      // 准备创建子主题的数据
      const subThemeData = {
        parentId: Number(form.value.category),  // 下拉菜单选择的父主题ID
        name: form.value.name,
        label: form.value.name,  // 使用name作为label
        description: form.value.description,
        coverImage: form.value.coverImage,
        sortOrder: 0
      }

      // 调用创建子主题接口
      const response = await createSubTheme(subThemeData)

      if (response.success) {
        ElMessage.success('子主题创建成功')
        emit('submit', response.data)
        dialogVisible.value = false
      } else {
        ElMessage.error(response.message || '创建子主题失败')
      }
    }
  } catch (error) {
    console.error('创建子主题失败:', error)
    ElMessage.error('创建子主题失败，请重试')
  } finally {
    loading.value = false
  }
}

</script>


<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-textarea .el-input__count) {
  background: transparent;
}

/* 封面上传样式 */
.cover-upload {
  width: 100%;
}

.cover-preview {
  position: relative;
  width: 100%;
  height: 200px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.cover-preview:hover .cover-overlay {
  opacity: 1;
}

.cover-placeholder {
  width: 100%;
  height: 200px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  cursor: pointer;
  transition: border-color 0.3s;
}

.cover-placeholder:hover {
  border-color: #409eff;
  color: #409eff;
}

.cover-placeholder .el-icon {
  font-size: 40px;
  margin-bottom: 8px;
}

.cover-text {
  font-size: 14px;
}

.cover-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.unit-text {
  margin-left: 10px;
  color: #606266;
}
</style>
